package org.xfy.sys.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.xfy.base.util.AjaxResult;
import org.xfy.base.util.ErrorCode;
import org.xfy.org.exception.BusinessException;
import org.xfy.sys.domain.Menu;
import org.xfy.sys.domain.Role;
import org.xfy.sys.domain.dto.RoleDto;
import org.xfy.sys.mapper.RoleMapper;
import org.xfy.sys.service.IRoleService;
import org.xfy.base.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void add(RoleDto role) {
        Role role1 = new Role();
        BeanUtils.copyProperties(role, role1);
        super.add(role1);
        roleMapper.addRoleAndMenu(role1.getId(), role.getMenuId());
        roleMapper.addRoleAndPermission(role1.getId(), role.getPermissionId());
    }


    @Override
    @Transactional
    public void update(RoleDto role) {
        Role role2 = roleMapper.findBysn(role.getId(), role.getSn());
        if (role2 != null) {
            throw new BusinessException(ErrorCode.Besiness_Role_sn_ERROR.getCode());
        }
        Role role1 = new Role();
        BeanUtils.copyProperties(role, role1);
        super.update(role1);
        roleMapper.delRoleAndMenu(role1.getId());
        roleMapper.delRoleAndPermission(role1.getId());
        roleMapper.addRoleAndMenu(role1.getId(), role.getMenuId());
        roleMapper.addRoleAndPermission(role1.getId(), role.getPermissionId());
    }

    @Override
    public AjaxResult getPermissionByroleId(Long roleId) {
        return AjaxResult.me().setResultObj(roleMapper.getPermissionByroleId(roleId));
    }

    @Override
    public AjaxResult getMenu(Long roleId) {
        List<Menu> Menus = roleMapper.findMenuByroleId(roleId);
        List<List<Long>> list=new ArrayList<>();
        for (int i = 0; i < Menus.size(); i++) {
            ArrayList<Long> list1 = new ArrayList<>();
            Menu menu = Menus.get(i);
            list1.add(menu.getParentId());
            list1.add(menu.getId());
            list.add(list1);
        }
        return AjaxResult.me().setResultObj(list);
    }

}
